﻿using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace Ning.Preferences
{

    public class DocHandler : IPreferences
    {

        public DocHandler()
        {
            Load();
        }

        public Dictionary<string, string> dictionary = new Dictionary<string, string>();

        /// <summary>
        /// Wrapper for the same method in PlayerPrefs - note that useSecurePrefs is ignored.
        /// </summary>
        public override float GetFloat(string key, float defaultValue = 0.0f)
        {
            var temp = GetValue(key, defaultValue.ToString());
            return float.Parse(temp);
        }

        /// <summary>
        /// Wrapper for the same method in PlayerPrefs - note that useSecurePrefs is ignored.
        /// </summary>
        public override int GetInt(string key, int defaultValue = 0)
        {
            var temp = GetValue(key, defaultValue.ToString());
            return System.Int32.Parse(temp);
        }

        /// <summary>
        /// Wrapper for the same method in PlayerPrefs - note that useSecurePrefs is ignored.
        /// </summary>
        public override string GetString(string key, string defaultValue = "")
        {
            return GetValue(key, defaultValue.ToString());
        }

        /// <summary>
        /// Get boolean preferences
        /// </summary>
        public override bool GetBool(string key, bool defaultValue = false)
        {
            var temp = GetValue(key, defaultValue.ToString());
            return temp.ToLower() == true.ToString().ToLower();
        }

        /// <summary>
        /// Wrapper for the same method in PlayerPrefs.
        /// </summary>
        public override bool HasKey(string key)
        {
            return dictionary.ContainsKey(key);
        }

        /// <summary>
        /// Wrapper for the same method in PlayerPrefs - note that useSecurePrefs is ignored.
        /// </summary>
        public override void SetFloat(string key, float value)
        {
            SetValue(key, value.ToString());
        }

        /// <summary>
        /// Wrapper for the same method in PlayerPrefs - note that useSecurePrefs is ignored.
        /// </summary>
        public override void SetInt(string key, int value)
        {
            SetValue(key, value.ToString());
        }

        /// <summary>
        /// Wrapper for the same method in PlayerPrefs - note that useSecurePrefs is ignored.
        /// </summary>
        public override void SetString(string key, string value)
        {
            SetValue(key, value.ToString());
        }

        /// <summary>
        /// Set boolean preferences
        /// </summary>
        public override void SetBool(string key, bool value)
        {
            SetValue(key, value.ToString().ToLower());
        }

        /// <summary>
        /// Wrapper for the same method in PlayerPrefs.
        /// </summary>
        public override void DeleteAll()
        {
            dictionary.Clear();
        }

        /// <summary>
        /// Wrapper for the same method in PlayerPrefs.
        /// </summary>
        public override void DeleteKey(string key)
        {
            dictionary.Remove(key);
        }

        public override Vector2? GetVector2(string key, Vector2? defaultValue = null)
        {
            var temp = GetValue(key, Vector2ToString(defaultValue));
            return StringToVector2(temp);
        }

        public override Vector3? GetVector3(string key, Vector3? defaultValue = null)
        {
            var temp = GetValue(key, Vector3ToString(defaultValue));
            return StringToVector3(temp);
        }

        public override Color? GetColor(string key, Color? defaultValue = null)
        {
            var temp = GetValue(key, ColorToString(defaultValue));
            return StringToColor(temp);
        }

        public override void SetVector2(string key, Vector2? value)
        {
            SetValue(key, Vector2ToString(value));
        }

        public override void SetVector3(string key, Vector3? value)
        {
            SetValue(key, Vector3ToString(value));
        }

        public override void SetColor(string key, Color? value)
        {
            SetValue(key, ColorToString(value));
        }

        /// <summary>
        /// 保存JSON数据到本地的方法
        /// </summary>
        /// <param name="player">要保存的对象</param>
        public override void Save()
        {
            try
            {
                //找到当前路径
                FileStream fs = new FileStream(Global.filePath, FileMode.Create, FileAccess.Write);

                //判断有没有文件，有则打开文件，，没有创建后打开文件
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                string json = JsonMapper.ToJson(dictionary);

                sw.WriteLine(json);
                sw.Close();
                sw.Dispose();
                PlayerPrefs.Save();
            }
            catch (System.Exception)
            {
                ReadFileFail();
            }
        }

        /// <summary>
        /// 读取保存数据的方法
        /// </summary>
        public void Load()
        {
            var filePath = Global.filePath;
            if (File.Exists(filePath))
            {
                try
                {
                    FileStream fs = new FileStream(filePath, FileMode.Open);
                    StreamReader sr = new StreamReader(fs, Encoding.UTF8);
                    using (TextReader reader = new StringReader(sr.ReadLine()))
                    {
                        JsonData jd = JsonMapper.ToObject(reader.ReadLine());

                        IDictionary dict = jd as IDictionary;
                        foreach (string key in dict.Keys)
                        {
                            if (dictionary.ContainsKey(key))
                            {
                                dictionary[key] = jd[key].ToString();
                            }
                            else
                            {
                                dictionary.Add(key, jd[key].ToString());
                            }
                        }
                    }
                    if (fs != null)
                        fs.Close();
                    if (sr != null)
                        sr.Close();
                }
                catch (System.Exception)
                {
                    ReadFileFail();
                }
            }
        }

        private string GetValue(string key, string defaultValue)
        {
            if (HasKey(key))
            {
                return dictionary[key];
            }
            else
            {
                dictionary.Add(key, defaultValue);
                return defaultValue;
            }
        }
        private void SetValue(string key, string value)
        {
            if (HasKey(key))
            {
                dictionary[key] = value;
            }
            else
            {
                dictionary.Add(key, value);
            }
        }

        private void ReadFileFail()
        {
            //Global.userInfo.IsRegister = false;
            //Global.userInfo.FilePath = "";
            //Global.userInfo.Invite = "";
            //Global.userInfo.AppV = "";
            //Global.userInfo.Channel = "";
            //Global.userInfo.UID = "";
            //Global.userInfo.Phone = "";
            //Global.userInfo.VipLevel = "";
            //Global.userInfo.Name = "";
            //Global.userInfo.Nickname = "";
            //Global.userInfo.unionid = "";
            //Global.userInfo.mskk_openid = "";
            //Global.userInfo.School = "";
            //Global.userInfo.Sex = "男";
            //Global.userInfo.BabyDay = 0;
            //Global.userInfo.BabyMonth = 0;
            //Global.userInfo.BabyYear = 0;
            //PlayerPrefs.Save();
            //ToolKit.loadName = "LoginScene";
            //UnityEngine.SceneManagement.SceneManager.LoadScene("loading");
        }

    }
}
